<template>
  <div>
    <el-form-item label="导入模板">
      <el-radio-group v-model="value.templateType" style="width: 100%">
        <el-radio label="SYSTEM">系统</el-radio>
        <el-radio label="CUSTOM">自定义</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="模板" style="display: block">
      <el-select
        v-if="value.templateType === 'SYSTEM'"
        size="small"
        style="width: 100%"
        v-model="value.systemplateKey"
        placeholder="请选择模板"
        clearable
      >
        <el-option
          v-for="(item, index) in templateArr"
          :key="index"
          :value="item.key"
          :label="item.name"
        >
        </el-option>
      </el-select>
      <div v-if="value.templateType === 'CUSTOM'">
        <div class="filebox ks-row-middle bgwh" v-if="!!value.tempalteURL">
          <div class="g3 ks-col ell f14">
            {{ value.tempalteURL }}
          </div>
          <el-button
            type="text"
            icon="el-icon-download"
            @click="download(value.tempalteURL)"
            >下载</el-button
          >
          <el-button
            type="text"
            icon="el-icon-delete"
            @click="value.tempalteURL = ''"
            >删除
          </el-button>
        </div>
        <common-upload
          v-else
          client
          @success="handleUploadSuccess"
          accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        >
          <el-button icon="el-icon-upload2" size="mini">上传</el-button>
        </common-upload>
      </div>
    </el-form-item>
    <el-form-item label="导入参数">
      <template slot="label">
        导入参数
        <el-tooltip
          effect="dark"
          content="导入参数中可以指定导入模型中字段固定值，如果该字段已经在模板中存在则会覆盖模板中的字段值"
          placement="top-start"
        >
          <i class="el-icon-question" />
        </el-tooltip>
      </template>
      <div class="ks-row-middle g6 poi codebg ks-col" @click="editJsx()">
        <div class="g9 f12 ks-col pl5 pr5">
          {{
            value.templateValues
              ? "export default function..."
              : "（空）点击添加自定义函数"
          }}
        </div>
      </div>
    </el-form-item>
    <el-form-item label="数据起始行号" v-if="value.templateType === 'CUSTOM'">
      <el-input-number
        :min="value.headerRowNo + 1"
        size="small"
        style="width: 100%"
        v-model="value.startRowNo"
        controls-position="right"
      ></el-input-number>
    </el-form-item>
    <el-form-item label="标题行号" v-if="value.templateType === 'CUSTOM'">
      <el-input-number
        size="small"
        style="width: 100%"
        v-model="value.headerRowNo"
        controls-position="right"
        :max="value.startRowNo - 1"
        :min="1"
      ></el-input-number>
    </el-form-item>
    <div>
      <el-form-item
        label="自定义业务服务"
        v-if="value.templateType === 'CUSTOM'"
      >
        <el-switch v-model="value.customServe"></el-switch>
        <el-select
          v-if="value.customServe"
          v-model="value.processServeId"
          placeholder="默认"
          style="width: 160px"
          class="ml10"
        >
          <el-option
            :value="i.key"
            :label="i.name"
            v-for="(i, index) in btnServelist"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
    </div>
    <el-form-item label="设置超时时间（秒）" style="display: block">
      <el-switch v-model="value.timeoutFlag"></el-switch>
      <el-input-number
        class="ml10"
        v-if="value.timeoutFlag"
        v-model="value.timeout"
        size="small"
        style="width: 160px"
        controls-position="right"
        :min="1"
      >
      </el-input-number>
    </el-form-item>
    <el-form-item label="数据校验不通过">
      <el-radio-group v-model="value.importOnError" style="width: 100%">
        <el-radio :label="false">全部不导入</el-radio>
        <el-radio :label="true">正确数据导入</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="重复数据">
      <el-radio-group v-model="value.importOnRepeat" style="width: 100%">
        <el-radio :label="false">不导入</el-radio>
        <el-radio :label="true">更新</el-radio>
      </el-radio-group>
    </el-form-item>
  </div>
</template>

<script>
import { getHmexceltemplateList } from "@/apis/paas/HmExcelTemplateController.js";
import { downloadFileSrc } from "@/utils/util.js";
import { getBasePath } from "@/config/api.config";
import monacoEditor from "../../monacoEditor/index";
import { getHmhttprequestdefinitionList } from "@/apis/paas/HmHttpRequestDefinitionController.js";

const template = `/**
 * context    页面工具类对象,
 * rootScope  页面公共事件对象
 * row 当前行
 * @returns  Object
 */
function getQueryData(context,rootScope,row) {
  return {}
}`;
export default {
  name: "ImportBtn",
  components: {},
  props: ["value", "formOption"],
  data() {
    return {
      templateArr: [], // 导入模板list
      btnServelist: [], // 自定义业务服务
    };
  },
  watch: {
    "value.templateType": {
      async handler(val) {
        if (val === "") {
          // 初始化
          this.$set(this.value, "templateType", "SYSTEM");
          this.$set(this.value, "systemplateKey", "");
          this.$set(this.value, "templateValues", "");
          this.$set(this.value, "tempalteURL", "");
          this.$set(this.value, "templateFile", "");
          this.$set(this.value, "templateFileName", "");
          this.$set(this.value, "timeoutFlag", false);
          this.$set(this.value, "importOnError", false);
          this.$set(this.value, "importOnRepeat", false);
        }
        if (val === "SYSTEM") {
          await this.loadData();
        }
        if (val === "CUSTOM") {
          this.setValue("systemplateKey", "");
          if (!this.value.startRowNo) {
            this.$set(this.value, "startRowNo", 2);
          }
          if (!this.value.headerRowNo) {
            this.$set(this.value, "headerRowNo", 1);
          }
          if (this.value.customServe === undefined) {
            this.$set(this.value, "customServe", false);
          }
        }
      },
      immediate: true,
    },
    "value.systemplateKey": {
      handler(val) {
        if (val) {
          const file = this.templateArr?.filter((item) => {
            return item.key === val;
          })[0];
          this.setValue("templateFile", file?.templateFile || "");
          this.setValue("templateFileName", file?.name || "");
        }
      },
    },
    "value.customServe": {
      handler(val) {
        if (val) {
          if (!this.value.customServe) {
            this.$set(this.value, "processServeId", "");
          }
        }
      },
    },
    "value.timeoutFlag": {
      handler(val) {
        if (val) {
          if (!this.value.timeout) {
            this.$set(this.value, "timeout", 20);
          }
        }
      },
    },
    "value.customServe": {
      async handler(val) {
        if (val) {
          if (val) {
            const { modelCode } = this.formOption;
            let btnServelist = await getHmhttprequestdefinitionList({
              modelCode,
            });
            this.btnServelist = btnServelist.filter((i) => {
              return (
                i.serviceType !== "BUILT_IN" ||
                i.key === "selectList" ||
                i.key === "selectByPage" ||
                i.key === "selectByIds"
              );
            });
          }
        }
      },
      immediate: true,
    },
  },
  methods: {
    handleUploadSuccess(src) {
      this.setValue("tempalteURL", src);
    },
    download(fileUrl) {
      downloadFileSrc(
        getBasePath(fileUrl),
        fileUrl?.split("/")?.reverse()[0] || "模板"
      );
    },
    async loadData() {
      const { modelCode } = this.formOption;
      const data = await getHmexceltemplateList({
        modelCode: modelCode,
      });
      this.templateArr = data.filter((item) => item.type === "IMPORT");
    },
    editJsx() {
      let jsx = this.value.templateValues || template;
      monacoEditor.showEdit(decodeURIComponent(jsx)).then((res) => {
        this.setValue("templateValues", encodeURIComponent(res));
      });
    },
    setValue(key, value) {
      if (this.value[key] === undefined) {
        this.$set(this.value, key, value);
      } else {
        this.value[key] = value;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.filebox {
  max-width: 400px;
  border-radius: 2px;
  background: #f4f9ff;
}

.codebg {
  border: 1px solid #f1f1f1;
  width: 200px;
  &:hover {
    background-color: #f3f9ff;
  }
}
</style>
